<template>
  <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false" @close="closeModal">
    <el-form ref="form" :model="form" :show-message="false" label-width="120px">
      <el-form-item label="药材名称1" prop="conflictId" required>
        <SelectDrug ref="SelectDrug1" :defaultValue.sync="form.conflictId" />
      </el-form-item>
      <el-form-item label="药材名称2" prop="materialsId" required>
        <SelectDrug ref="SelectDrug2" :defaultValue.sync="form.materialsId" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import SelectDrug from "./selectDrug";
import { addClash, updateClash, getClashDetails } from "@/api/saas/tcm.js";

export default {
  components: {
    SelectDrug,
  },
  data() {
    return {
      title: "新建配伍禁忌",
      open: false,
      form: {
        id: undefined,
        conflictId: undefined,
        materialsId: undefined,
      },
    };
  },
  methods: {
    openModal(id) {
      this.title = id ? '编辑配伍禁忌' : '新建配伍禁忌';
      this.open = true;
      this.form.id = id || undefined;
      this.form.id && this.getData();
    },
    closeModal() {
      this.$refs["form"].resetFields();
      this.$refs.SelectDrug1.remoteMethod('');
      this.$refs.SelectDrug2.remoteMethod('');
      Object.assign(this.$data, this.$options.data()); // 存在自定义校验规则不能重置data
    },
    // 获取详情
    getData() {
      getClashDetails(this.form.id).then((res) => {
        this.form = res.data;
      });
    },
    submitForm() {
      const that = this;
      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          if(that.form.conflictId === that.form.materialsId){
            that.$message.error('不能配置相同药材')
            return
          }
          if (that.form.id) {
            await updateClash(that.form);
          } else {
            await addClash(that.form);
          }
          that.$message.success(that.form.id ? "修改成功" : "新增成功");
          that.$emit("refresh");
          that.closeModal();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
